package com.example.wepeaker

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.aimei.wepeaker.R
import java.io.BufferedInputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    
    private lateinit var analyzeButton: Button
    private lateinit var resultText: TextView
    
    private lateinit var speaker: Speaker
    
    private lateinit var audioData: MutableList<Float>
    private lateinit var executorService: ExecutorService
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        analyzeButton = findViewById(R.id.analyzeButton)
        resultText = findViewById(R.id.resultText)
        
        speaker = Speaker(this)
        audioData = mutableListOf()
        executorService = Executors.newSingleThreadExecutor()
        
        // Load audio data from assets when app starts
        loadAudioFromAssets()
        
        analyzeButton.setOnClickListener {
            analyzeAudio()
        }
    }
    
    private fun loadAudioFromAssets() {
        executorService.execute {
            try {
                audioData.clear()
                
                assets.open("together.WAV").use { assetInputStream ->
                    val bufferedInputStream = BufferedInputStream(assetInputStream)
                    
                    // Skip WAV header (44 bytes)
                    bufferedInputStream.skip(44)
                    
                    val buffer = ByteArray(2048)
                    var bytesRead: Int
                    
                    while (bufferedInputStream.read(buffer).also { bytesRead = it } != -1) {
                        val byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead)
                        byteBuffer.order(ByteOrder.LITTLE_ENDIAN)
                        
                        for (i in 0 until bytesRead / 2) {
                            val sample = byteBuffer.getShort(i * 2).toInt()
                            val normalizedSample = sample / 32768.0f // Normalize to [-1.0, 1.0]
                            audioData.add(normalizedSample)
                        }
                    }
                }
                
                runOnUiThread {
                    resultText.setText(R.string.file_ready)
                    analyzeButton.isEnabled = true
                }
                
                Log.d(TAG, "Audio loaded from assets, samples: ${audioData.size}")
                
            } catch (e: Exception) {
                Log.e(TAG, "Error loading audio from assets", e)
                runOnUiThread {
                    resultText.text = getString(R.string.error_loading, e.message)
                }
            }
        }
    }
    
    private fun analyzeAudio() {
        if (audioData.isEmpty()) {
            resultText.setText(R.string.no_audio_data)
            return
        }
        
        resultText.setText(R.string.analyzing)
        analyzeButton.isEnabled = false
        
        executorService.execute {
            try {
                val audioFloatArray = audioData.toFloatArray()
                val purity = speaker.run(audioFloatArray)
                
                runOnUiThread {
                    val purityPercentage = (purity * 100).toInt()
                    
                    // Use a StringBuilder to avoid concatenation warnings
                    val resultBuilder = StringBuilder()
                    resultBuilder.append(getString(R.string.voice_purity_result, purityPercentage))
                    resultBuilder.append("\n")
                    resultBuilder.append(
                        if (purity > 0.65) getString(R.string.single_speaker) 
                        else getString(R.string.multiple_speakers)
                    )
                    resultText.text = resultBuilder.toString()
                    
                    analyzeButton.isEnabled = true
                }
            } catch (e: Exception) {
                Log.e(TAG, "Error analyzing audio", e)
                runOnUiThread {
                    resultText.text = getString(R.string.error_analyzing, e.message)
                    analyzeButton.isEnabled = true
                }
            }
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        executorService.shutdown()
        speaker.close()
    }
}